#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <string.h>
#include <asm-generic/socket.h>
#include <errno.h>
#include "parse.h"
#include <asm-generic/socket.h>
#include <errno.h>
#include "logger.h"
#include "response.h"
#include <sys/select.h>

#define ECHO_PORT 9999
#define BUF_SIZE 4096
#define MAX_HEADER_SIZE 8192
#define MAX_CONNECTIONS 1024

int sock = -1;
char buf[BUF_SIZE];

int close_socket(int sock) {
    if (close(sock)) {
        fprintf(stderr, "Failed closing socket.\n");
        return 1;
    }
    return 0;
}

void handle_signal(const int sig) {
    if (sock != -1) {
        fprintf(stderr, "\nReceived signal %d. Closing socket.\n", sig);
        close_socket(sock);
    }
    exit(0);
}

void handle_sigpipe(const int sig) 
{
    if (sock != -1) {
        return;
    }
    exit(0);
}

int main(int argc, char *argv[]) {
    /* register signal handler */
    /* process termination signals */
    signal(SIGTERM, handle_signal);
    signal(SIGINT, handle_signal);
    signal(SIGSEGV, handle_signal);
    signal(SIGABRT, handle_signal);
    signal(SIGQUIT, handle_signal);
    signal(SIGTSTP, handle_signal);
    signal(SIGFPE, handle_signal);
    signal(SIGHUP, handle_signal);
    /* normal I/O event */
    signal(SIGPIPE, handle_sigpipe);

    struct sockaddr_in addr, cli_addr;
    fprintf(stdout, "----- Liso Server -----\n");

    /* all networked programs must create a socket */
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "Failed creating socket.\n");
        return EXIT_FAILURE;
    }
    /* set socket SO_REUSEADDR | SO_REUSEPORT */
    int opt = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        fprintf(stderr, "Failed setting socket options.\n");
        return EXIT_FAILURE;
    }

    addr.sin_family = AF_INET; // ipv4
    addr.sin_port = htons(ECHO_PORT);
    addr.sin_addr.s_addr = INADDR_ANY;

    /* servers bind sockets to ports---notify the OS they accept connections */
    if (bind(sock, (struct sockaddr *) &addr, sizeof(addr))) {
        close_socket(sock);
        fprintf(stderr, "Failed binding socket.\n");
        return EXIT_FAILURE;
    }

    if (listen(sock, 5)) {
        close_socket(sock);
        fprintf(stderr, "Error listening on socket.\n");
        return EXIT_FAILURE;
    }

    fd_set master;    // 主文件描述符集合
    fd_set readfds;   // 临时文件描述符集合
    int fdmax;        // 最大文件描述符编号

    FD_ZERO(&master); // 清空主文件描述符集合
    FD_ZERO(&readfds);

    FD_SET(sock, &master); // 将监听套接字添加到主文件描述符集合中
    fdmax = sock;

    while (1) {
        readfds = master; // 复制主文件描述符集合到临时文件描述符集合

        if (select(fdmax + 1, &readfds, NULL, NULL, NULL) == -1) {
            perror("select");
            return EXIT_FAILURE;
        }

        // 遍历所有文件描述符
        int i = 0;
        for (i = 0; i <= fdmax; i++) {
            if (FD_ISSET(i, &readfds)) { // 如果文件描述符变为可读状态
                if (i == sock) { // 如果是监听套接字
                    socklen_t cli_size = sizeof(cli_addr);
                    int newfd = accept(sock, (struct sockaddr *) &cli_addr, &cli_size);
                    if (newfd == -1) {
                        perror("accept");
                    } else {
                        FD_SET(newfd, &master); // 将新的客户端套接字添加到主文件描述符集合中
                        if (newfd > fdmax) {
                            fdmax = newfd; // 更新最大文件描述符编号
                        }
                        fprintf(stdout, "New connection from %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
                    }
                } else { // 如果是客户端套接字
                    memset(buf, 0, BUF_SIZE);
                    int readret = recv(i, buf, BUF_SIZE, 0);
                    // 初始化日志
                    if (init_loggers() != 0) {
                        return EXIT_FAILURE;
                    }
                    if (readret < 0) {
                        perror("recv");
                        close_socket(i);
                        FD_CLR(i, &master); // 从主文件描述符集合中移除该套接字
                    } else if (readret == 0) {
                        // 客户端关闭连接
                        fprintf(stdout, "Closed connection from %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
                        close_socket(i);
                        FD_CLR(i, &master); // 从主文件描述符集合中移除该套接字
                    } else {
                        fprintf(stdout, "Received (total %d bytes):\n%s \n", readret, buf); 
                        buf[readret] = '\0';

                        // 检查请求头部长度
                        if (strlen(buf) > MAX_HEADER_SIZE) {
                            if (send(i, RESPONSE_400, strlen(RESPONSE_400), 0) != (ssize_t)strlen(RESPONSE_400)) {
                                close_socket(i);
                                fprintf(stderr, "Error sending to client.\n");
                                FD_CLR(i, &master); // 从主文件描述符集合中移除该套接字
                                continue;
                            }
                            continue;
                        }

                        // 采用流水线方式
                        char *start = buf;
                        char *end;
                        while ((end = strstr(start, "\r\n\r\n")) != NULL) {
                            int request_size = end - start + 4; // 4是"\r\n\r\n"的长度
                            char request_buf[BUF_SIZE];
                            memcpy(request_buf, start, request_size);
                            request_buf[request_size] = '\0';

                            printf("received: \n%s\r\n\r\n", request_buf);

                            // 解析请求头
                            Request *request = parse(request_buf, request_size, i);
                            // 设置连接类型
                            int keep_alive = 1;
                            if (request != NULL) keep_alive = get_connection_type(request);
                            // 检查是否有请求体，如果有则拼接到请求头后面，并更新end指针
                            char body[BUF_SIZE] = {0};
                            if (request!= NULL && get_header_value(request, "Content-Type") != NULL && get_header_value(request, "Content-Length")!= NULL) {
                                char *body_start = end + 4; 
                                int body_size = atoi(get_header_value(request, "Content-Length"));
                                if (body_size > 0) {
                                    memcpy(body, body_start, body_size);
                                    body[body_size] = '\0';
                                }

                                // int real_size = 0;
                                // char *real_start = strstr(body_start, "{");
                                // char *real_end = strstr(body_start, "}");
                                // real_size = real_end - real_start + 1;
                                // printf("real_size: %d\ncontent_length: %d\n", real_size, body_size);

                                end = body_start + body_size - 4; // 更新end指针

                                printf("body: \n%s\r\n", body);
                            }

                            // 设置响应头
                            char response[BUF_SIZE * 2];
                            if (set_response(request, &cli_addr, response, sizeof(response), ECHO_PORT, body)) {
                                // 将响应发送给客户端
                                if (send(i, response, strlen(response), 0) != (ssize_t)strlen(response)) {
                                    close_socket(i);  // 关闭客户端套接字
                                    log_error("Error sending to client", errno); // 已有日志记录
                                    fprintf(stderr, "Error sending to client.\n");
                                    FD_CLR(i, &master); // 从主文件描述符集合中移除该套接字
                                    break;
                                }
                            }
                            fprintf(stdout, "response: \n%s\r\n\r\n", response);
                            start = end + 4; // Move to the start of the next request
                        }
                        fprintf(stdout, "Send back\n");
                    }
                    close_loggers();
                }
            }
        }
    }
    close_socket(sock);
    return EXIT_SUCCESS;
}